﻿using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 生产系统-生产退料
    /// </summary>
    [Route("ProductionMaterialReturn")]
    public class ProductionMaterialReturnController : Controller
    {
        private readonly IProductionMaterialReturnServices productionMaterialReturnServices;

        public ProductionMaterialReturnController(IProductionMaterialReturnServices productionMaterialReturnServices )
        {
            this.productionMaterialReturnServices = productionMaterialReturnServices;
        }
        
        /// <summary>
        /// 解析仓库字符串，提取三级仓库信息
        /// </summary>
        /// <param name="warehouseString">仓库字符串，格式如：预置仓库 > 1号仓1区 > 1号仓1区1位 或 cz_1_1</param>
        /// <returns>三级仓库信息</returns>
        private (string Level1, string Level2, string Level3) ParseWarehouseString(string warehouseString)
        {
            if (string.IsNullOrEmpty(warehouseString))
            {
                return ("", "", "");
            }
            
            // 清理字符串
            warehouseString = warehouseString.Trim();
            
            // 处理包含 ">" 分隔符的格式
            if (warehouseString.Contains(">"))
            {
                var parts = warehouseString.Split('>', StringSplitOptions.RemoveEmptyEntries)
                                          .Select(p => p.Trim())
                                          .ToArray();
                
                return (
                    parts.Length > 0 ? parts[0] : "",
                    parts.Length > 1 ? parts[1] : "",
                    parts.Length > 2 ? parts[2] : ""
                );
            }
            
            // 处理简化格式，如 cz_1_1, yz_2_3 等
            if (warehouseString.Contains("_"))
            {
                var parts = warehouseString.Split('_');
                if (parts.Length >= 3)
                {
                    // 解析为：仓库代码_区域_库位
                    var warehouseCode = parts[0];  // cz, yz 等
                    var areaCode = parts[1];       // 1, 2 等
                    var locationCode = parts[2];   // 1, 2 等
                    
                    var level1 = MapWarehouseCode(warehouseCode);
                    var level2 = $"{areaCode}号仓{areaCode}区";  
                    var level3 = $"{areaCode}号仓{areaCode}区{locationCode}位";
                    
                    return (level1, level2, level3);
                }
                else if (parts.Length == 2)
                {
                    // 只有仓库和区域
                    var warehouseCode = parts[0];
                    var areaCode = parts[1];
                    
                    var level1 = MapWarehouseCode(warehouseCode);
                    var level2 = $"{areaCode}号仓{areaCode}区";
                    return (level1, level2, "");
                }
                else if (parts.Length == 1)
                {
                    // 只有仓库代码
                    var level1 = MapWarehouseCode(parts[0]);
                    return (level1, "", "");
                }
            }
            
            // 处理不包含下划线的简单代码
            if (warehouseString.Length <= 5 && !warehouseString.Contains(" "))
            {
                var mappedName = MapWarehouseCode(warehouseString);
                if (mappedName != warehouseString)
                {
                    return (mappedName, "", "");
                }
            }
            
            // 处理其他可能的格式
            // 如果字符串看起来像是完整的仓库路径但没有 ">" 分隔符
            if (warehouseString.Contains("仓") || warehouseString.Contains("区") || warehouseString.Contains("位"))
            {
                // 将整个字符串作为第一级
                return (warehouseString, "", "");
            }
            
            // 如果无法解析，将整个字符串放在第一级
            return (warehouseString, "", "");
        }
        
        /// <summary>
        /// 映射仓库代码到仓库名称
        /// </summary>
        /// <param name="code">仓库代码</param>
        /// <returns>仓库名称</returns>
        private string MapWarehouseCode(string code)
        {
            if (string.IsNullOrEmpty(code))
                return code;
                
            return code.ToLower() switch
            {
                "cz" => "测试仓库",
                "yz" => "预置仓库", 
                "yg" => "云中港项目",
                "ck" => "出口仓库",
                "zx" => "中心仓库",
                "bj" => "备件仓库",
                "yl" => "原料仓库",
                "cp" => "成品仓库",
                "bc" => "半成品仓库",
                _ => code  // 如果没有映射，返回原代码
            };
        }
        
        /// <summary>
        /// 添加生产退料视图
        /// </summary>
        /// <returns></returns>
        [HttpGet("AddProductMaterReturn")]
        public IActionResult AddProductMaterReturn()
        {
            return View();
        }
        
        /// <summary>
        /// 生产退料列表页面
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetProductMaterReturn")]
        public IActionResult GetProductMaterReturn()
        {
            return View();
        }
        
        /// <summary>
        /// 获取生产退料数据列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetProductionMaterialReturnList")]
        public async Task<JsonResult> GetProductionMaterialReturnList(int page = 1, int limit = 10, string returnOrderCode = "", string returnOrderName = "", string productionWorkOrder = "", string warehouse = "")
        {
            try
            {
                // 调用服务层的方法来获取数据
                var result = await productionMaterialReturnServices.GetProductionMaterialReturnList(page, limit, returnOrderCode, returnOrderName, productionWorkOrder, warehouse);
                
                // 转换数据格式以匹配前端表格需要的字段
                var transformedData = result.ListDate.Select(item => 
                {
                    // 解析仓库层级信息
                    var warehouseParts = ParseWarehouseString(item.ReceiveWarehouse);
                    
                    // 添加调试信息
                    System.Diagnostics.Debug.WriteLine($"原始仓库: {item.ReceiveWarehouse}, 解析结果: L1={warehouseParts.Level1}, L2={warehouseParts.Level2}, L3={warehouseParts.Level3}");
                    
                    return new
                    {
                        id = item.Id,
                        returnOrderCode = item.ReturnOrderCode,
                        returnOrderName = item.ReturnOrderName,
                        productionWorkOrder = item.ProductionWorkOrder,
                        warehouseLevel1 = warehouseParts.Level1,
                        warehouseLevel2 = warehouseParts.Level2,
                        warehouseLevel3 = warehouseParts.Level3,
                        returnDate = item.ReturnDate.ToString("yyyy-MM-dd"),
                        status = "草稿",
                        actions = ""
                    };
                }).ToList();
                
                return Json(new { 
                    code = 0, 
                    msg = "", 
                    count = result.PageCount, 
                    data = transformedData 
                });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, count = 0, data = new List<object>() });
            }
        }
        
        /// <summary>
        /// 保存生产退料数据
        /// </summary>
        /// <param name="dto">退料数据</param>
        /// <returns></returns>
        [HttpPost("SaveProductionMaterialReturn")]
        public async Task<JsonResult> SaveProductionMaterialReturn([FromBody] ProductionMaterialReturnDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Json(new { success = false, message = "数据不能为空" });
                }

                // 调用服务层保存数据
                var result = await productionMaterialReturnServices.AddPMateriaReturn(dto);
                
                if (result > 0)
                {
                    return Json(new { success = true, message = "保存成功" });
                }
                else
                {
                    return Json(new { success = false, message = "保存失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        
        /// <summary>
        /// 测试查看数据库中的原始数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("TestWarehouseData")]
        public async Task<JsonResult> TestWarehouseData()
        {
            try
            {
                var allData = await productionMaterialReturnServices.GetPMateriaReturn();
                
                var testData = allData.Select(item => new
                {
                    id = item.Id,
                    returnOrderCode = item.ReturnOrderCode,
                    returnOrderName = item.ReturnOrderName,
                    productionWorkOrder = item.ProductionWorkOrder,
                    originalWarehouse = item.ReceiveWarehouse,
                    parsedWarehouse = ParseWarehouseString(item.ReceiveWarehouse),
                    returnDate = item.ReturnDate.ToString("yyyy-MM-dd")
                }).ToList();
                
                return Json(new { 
                    success = true, 
                    message = "数据获取成功",
                    count = testData.Count,
                    data = testData 
                });
            }
            catch (Exception ex)
            {
                return Json(new { 
                    success = false, 
                    message = ex.Message 
                });
            }
        }
        
        /// <summary>
        /// 简单的解析测试
        /// </summary>
        /// <returns></returns>
        [HttpGet("TestParsing")]
        public JsonResult TestParsing()
        {
            var testCases = new[]
            {
                "cz_1_1",
                "yz_2_3", 
                "yg_1_2",
                "预置仓库 > 1号仓1区 > 1号仓1区1位",
                "cz",
                "yz_1",
                ""
            };
            
            var results = testCases.Select(testCase => new
            {
                input = testCase,
                output = ParseWarehouseString(testCase)
            }).ToList();
            
            return Json(new 
            { 
                success = true, 
                data = results 
            });
        }
        
        /// <summary>
        /// 修改生产退料视图
        /// </summary>
        /// <returns></returns>
        [HttpGet("EditProductMaterReturn")]
        public IActionResult EditProductMaterReturn()
        {
            return View();
        }
        
        /// <summary>
        /// 根据ID获取生产退料数据
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns></returns>
        [HttpGet("GetProductionMaterialReturnById")]
        public async Task<JsonResult> GetProductionMaterialReturnById(int id)
        {
            try
            {
                var item = await productionMaterialReturnServices.GetPMateriaReturnById(id);
                
                if (item == null)
                {
                    return Json(new { 
                        success = false, 
                        message = "未找到指定的记录" 
                    });
                }
                
                return Json(new { 
                    success = true, 
                    message = "数据获取成功",
                    data = item
                });
            }
            catch (Exception ex)
            {
                return Json(new { 
                    success = false, 
                    message = ex.Message 
                });
            }
        }
        

        /// <summary>
        /// 更新生产退料数据
        /// </summary>
        /// <param name="dto">更新的退料数据</param>
        /// <returns></returns>
        [HttpPost("UpdateProductionMaterialReturn")]
        public async Task<JsonResult> UpdateProductionMaterialReturn([FromBody] ProductionMaterialReturnDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Json(new { success = false, message = "数据不能为空" });
                }

                System.Diagnostics.Debug.WriteLine($"控制器接收到更新数据: ID={dto.Id}, Name={dto.ReturnOrderName}, Code={dto.ReturnOrderCode}, WorkOrder={dto.ProductionWorkOrder}, Warehouse={dto.ReceiveWarehouse}, Date={dto.ReturnDate}, Remark={dto.Remark}");

                // 先检查记录是否存在
                var existingRecord = await productionMaterialReturnServices.GetPMateriaReturnById(dto.Id);
                if (existingRecord == null)
                {
                    // 获取所有记录用于调试
                    var allRecords = await productionMaterialReturnServices.GetPMateriaReturn();
                    var allIds = string.Join(", ", allRecords.Select(r => r.Id));
                    
                    System.Diagnostics.Debug.WriteLine($"控制器未找到ID={dto.Id}的记录，所有记录ID: {allIds}");
                    return Json(new { success = false, message = $"记录不存在，ID={dto.Id}。现有记录ID: {allIds}" });
                }

                System.Diagnostics.Debug.WriteLine($"控制器找到现有记录: ID={existingRecord.Id}, 原名称={existingRecord.ReturnOrderName}");

                // 直接使用现有实体，不要创建新实体
                // ABP框架的实体ID是只读的，不能直接设置
                
                // 更新现有实体的属性
                existingRecord.ReturnOrderName = dto.ReturnOrderName;
                existingRecord.ProductionWorkOrder = dto.ProductionWorkOrder;
                existingRecord.ReceiveWarehouse = dto.ReceiveWarehouse;
                existingRecord.ReturnDate = dto.ReturnDate;
                existingRecord.Remark = dto.Remark;

                System.Diagnostics.Debug.WriteLine($"控制器准备更新实体: ID={existingRecord.Id}, Name={existingRecord.ReturnOrderName}");

                // 调用服务层更新数据
                var result = await productionMaterialReturnServices.UpdatePMateriaReturn(existingRecord);
                
                System.Diagnostics.Debug.WriteLine($"控制器服务层返回结果: {result}");
                
                if (result > 0)
                {
                    return Json(new { success = true, message = "更新成功" });
                }
                else
                {
                    return Json(new { success = false, message = "更新失败，记录可能不存在" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"控制器更新异常: {ex.Message}, StackTrace: {ex.StackTrace}");
                return Json(new { success = false, message = $"更新异常: {ex.Message}" });
            }
        }
        
        /// <summary>
        /// 删除生产退料数据
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns></returns>
        [HttpPost("DeleteProductionMaterialReturn")]
        public async Task<JsonResult> DeleteProductionMaterialReturn(int id)
        {
            try
            {
                // 调用服务层删除数据
                var result = await productionMaterialReturnServices.DeletePMateriaReturn(id);
                
                if (result > 0)
                {
                    return Json(new { success = true, message = "删除成功" });
                }
                else
                {
                    return Json(new { success = false, message = "删除失败，记录可能不存在" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        
        /// <summary>
        /// 批量删除生产退料数据
        /// </summary>
        /// <param name="ids">记录ID数组</param>
        /// <returns></returns>
        [HttpPost("BatchDeleteProductionMaterialReturn")]
        public async Task<JsonResult> BatchDeleteProductionMaterialReturn([FromBody] int[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    return Json(new { success = false, message = "请选择要删除的记录" });
                }

                // 调用服务层批量删除数据
                var result = await productionMaterialReturnServices.BatchDeletePMateriaReturn(ids);
                
                return Json(new { 
                    success = true, 
                    message = $"成功删除 {result} 条记录" 
                });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        
        /// <summary>
        /// 测试记录是否存在
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns></returns>
        [HttpGet("TestRecordExists")]
        public async Task<JsonResult> TestRecordExists(int id)
        {
            try
            {
                var allRecords = await productionMaterialReturnServices.GetPMateriaReturn();
                var record = allRecords.FirstOrDefault(r => r.Id == id);
                
                if (record != null)
                {
                    return Json(new { 
                        success = true, 
                        message = "记录存在",
                        data = new {
                            id = record.Id,
                            returnOrderCode = record.ReturnOrderCode,
                            returnOrderName = record.ReturnOrderName,
                            productionWorkOrder = record.ProductionWorkOrder,
                            receiveWarehouse = record.ReceiveWarehouse,
                            returnDate = record.ReturnDate,
                            remark = record.Remark
                        }
                    });
                }
                else
                {
                    return Json(new { 
                        success = false, 
                        message = $"未找到ID为 {id} 的记录",
                        allIds = allRecords.Select(r => r.Id).ToList()
                    });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        
        /// <summary>
        /// 调试所有记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("DebugAllRecords")]
        public async Task<JsonResult> DebugAllRecords()
        {
            try
            {
                var allRecords = await productionMaterialReturnServices.GetPMateriaReturn();
                
                return Json(new { 
                    success = true, 
                    message = $"总共找到 {allRecords.Count} 条记录",
                    data = allRecords.Select(r => new {
                        id = r.Id,
                        returnOrderCode = r.ReturnOrderCode,
                        returnOrderName = r.ReturnOrderName,
                        productionWorkOrder = r.ProductionWorkOrder,
                        receiveWarehouse = r.ReceiveWarehouse,
                        returnDate = r.ReturnDate.ToString("yyyy-MM-dd"),
                        remark = r.Remark
                    }).ToList()
                });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message, stackTrace = ex.StackTrace });
            }
        }
        
        /// <summary>
        /// 测试接收数据格式
        /// </summary>
        /// <param name="dto">测试数据</param>
        /// <returns></returns>
        [HttpPost("TestDataReceive")]
        public JsonResult TestDataReceive([FromBody] ProductionMaterialReturnDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Json(new { success = false, message = "dto为null" });
                }

                return Json(new { 
                    success = true, 
                    message = "数据接收成功",
                    receivedData = new {
                        id = dto.Id,
                        returnOrderCode = dto.ReturnOrderCode,
                        returnOrderName = dto.ReturnOrderName,
                        productionWorkOrder = dto.ProductionWorkOrder,
                        receiveWarehouse = dto.ReceiveWarehouse,
                        returnDate = dto.ReturnDate,
                        remark = dto.Remark
                    }
                });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message, stackTrace = ex.StackTrace });
            }
        }
    }
}
